/*
 *   Copyright 2006 Wei Lian <lianwei3@gmail.com>
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation; either version 2
 *   of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include "header.h"
#include "socket.h"
#include "iosocket.h"
#include "iochannel.h"
#include "fork.h"
extern char new_url[];
static Channel iosocket = { 0, 0 };
static gchar sock_buf[320];
static int sock_read, sock_size;

int
launch_player ()
{
  int portnum = atoi (strstr (strstr (new_url, ":") + 1, ":") + 1);
  int sock = socket_connect (portnum);
  if (sock < 0)
    return -1;

  char str[320];
  sprintf (str,
	   "GET /live.asf HTTP/1.0\r\n"
	   "Host: 127.0.0.1:%d\r\n"
	   "Accept: */*\r\n"
	   "Accept-Language: en-us\r\n"
	   "Accept-Encoding: gzip, deflate\r\n"
	   "User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)\r\n"
	   "Connection: Keep-Alive\r\n\r\n", portnum);
  if (socket_send (sock, str, strlen (str)) == int (strlen (str)))
    {
      ///set initial value
      memset (sock_buf, 0, sizeof (sock_buf));
      sock_read = 0;
      sock_size = sizeof (sock_buf);
      ///put sock to io channel
      if (iosocket.tag == 0)
	{
	  create_iochannel (iosocket, sock, handle_io_socket);
	  return 0;
	}
      else
	close (sock);
    }
  else
    close (sock);
  return -1;
}

gboolean
handle_io_socket (GIOChannel * source, GIOCondition cond, gpointer d)
{
  GError *error = NULL;		// for error handling 
  GIOStatus status;		// save the reading status 
  gsize bytes_read;		// save the number of chars read 

  ////data availible
  if ((status =
       g_io_channel_read_chars (source, sock_buf + sock_read, sock_size,
				&bytes_read,
				&error)) == G_IO_STATUS_NORMAL &&
      bytes_read > 0)
    {
      sock_read += bytes_read;
      sock_size -= bytes_read;
      if (sock_size == 0)
	{
	  fork_player (new_url);
	  delete_iochannel (iosocket);
	  return FALSE;
	}
    }
  else if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF)
    {
      printf ("G_IO_STATUS_ERROR or G_IO_STATUS_EOF\n");
      delete_iochannel (iosocket);
      return FALSE;
    }
  else
    {
      printf ("rest options\n");
    }

  return TRUE;
}
